package cn.edu.ctbu.lablist.webapi;

import cn.edu.ctbu.lablist.domain.Student;
import cn.edu.ctbu.lablist.domain.Teacher;
import cn.edu.ctbu.lablist.service.StudentService;
import cn.edu.ctbu.lablist.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/login")
public class LoginRestController {
    @Autowired
    StudentService studentService;
    @Autowired
    TeacherService teacherService;
    @GetMapping("/user")
    public int user(HttpServletRequest httprequest, String username, String password){
        //判断用户名和密码是否存在
        List<Student> students = studentService.findByNoAndPassword(username,password);
        if (students.size() > 0){
            //如果存在，写入session
            HttpSession session = httprequest.getSession();
            session.setAttribute("userid",students.get(0).getId());
            session.setAttribute("user",students.get(0));
            return 1;//成功
        }else{
            List<Teacher> teachers = teacherService.findByNoAndPassword(username,password);
            if(teachers.size()>0){
                //如果存在，写入session
                HttpSession session = httprequest.getSession();
                session.setAttribute("userid",teachers.get(0).getId());
                session.setAttribute("user",teachers.get(0));
                return 2;//成功
            }
            //如果不存在，返回错误
            return -1;//不存在
            }}}
